<?php

namespace App\Http\Controllers;

use App\Models\Message;
use App\Models\SmsCode;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use App\Libs\Sms;
use Illuminate\Validation\Rule;

class UserController extends Controller
{
    public function info(Request $request)
    {
        $user = $request->user();
        $user->load('team');
        $user->load('org');
        $data = $user->toArray();
        $data['acl'] = $user->getAclList();

        if (!isset($data['org']) && $user->team) {
            $data['org'] = $user->team->org->toArray();
        }

        if (isset($data['org'])) {
            $data['org'] = [
                'name' => $data['org']['name'],
                'logo' => $data['org']['logo'],
            ];
        }

        return $this->returnJSON($data, 0, '', 200,[
            'UPDATE_UNREAD_COUNT' => Message::where('to_user_id', '=', $request->user()->id)->where('is_read', '=', 0)->count()
        ]);
    }

    public function getOrgInfo(Request $request) {
        $user = $request->user();

        if ($user->type != 3) {
            throw new \Exception('只有机构用户才能获取机构信息');
        }

        $team = $user->org;
        $data = $team->toArray();

        if (isset($data['user_id'])) {
            $user = User::findOrFail($data['user_id']);
            $data['username'] = $user->username;
            $data['email'] = $user->email;
        }
        return $this->returnJSON($data);
    }

    public function getPlatformInfo(Request $request) {
        $user = $request->user();

        if ($user->type != 5) {
            throw new \Exception('只有平台用户才能获取机构信息');
        }

        $team = $user->platform;
        $data = $team->toArray();

        if (isset($data['user_id'])) {
            $user = User::findOrFail($data['user_id']);
            $data['username'] = $user->username;
            $data['email'] = $user->email;
        }
        return $this->returnJSON($data);
    }

    public function saveOrgInfo(Request $request) {
        $user = $request->user();

        if ($user->type != 3) {
            throw new \Exception('只有机构用户才能保存机构信息');
        }

        $node = $user->org;

        $this->validate($request, [
            'name' => 'required|max:32',
            'type' => 'required|max:32',
            'contact_name' => 'required|max:32',
            'contact_phone' => 'required|max:32',
            'contact_email' => 'required|max:255',
            'address' => 'required',
            'corporate_name' => 'required|max:32',
            'corporate_id' => 'required|max:32',
            'corporate_phone' => 'required|max:32',
            'username' => 'max:64',
            'pwd' => 'max:64'
        ]);

        $data = $request->only([
            'name',
            'type',
            'logo',
            'contact_name',
            'contact_phone',
            'contact_email',
            'address',
            'corporate_name',
            'corporate_id',
            'corporate_phone',
            'quality',
            'username',
            'pwd',
            'email'
        ]);

        // default values;
        $data['business_licence'] = isset($data['business_licence']) ? $data['business_licence'] : '';
        $data['logo'] = isset($data['logo']) ? $data['logo'] : '';
        $data['quality'] = isset($data['quality']) ? $data['quality'] : '';

        $node->fill($data);
        if ($node->save()) {
            return $this->returnJSON(null, 0, '保存成功');
        }
        return $this->returnJSON(null, 500, '保存失败');
    }

    public function savePlatformInfo(Request $request)
    {
        $user = $request->user();

        if ($user->type != 5) {
            throw new \Exception('只有平台用户才能获取平台信息');
        }

        $node = $user->platform;
        $this->validate($request, [
            'name' => ['required', 'max:32', Rule::unique('platform')->ignore($user->platform_id)],
            'contact_name' => 'required|max:32',
            'contact_phone' => 'required|max:32',
            'contact_email' => 'required|max:255',
            'address' => 'required',
            'corporate_name' => 'required|max:32',
            'corporate_id' => 'required|max:32',
            'corporate_phone' => 'required|max:32',
            'username' => [
                'max:64',
                Rule::unique('user')->ignore($node->user_id)
            ],
            'pwd' => 'max:64'
        ]);

        $data = $request->only([
            'name',
            'logo',
            'contact_name',
            'contact_phone',
            'contact_email',
            'address',
            'corporate_name',
            'corporate_id',
            'corporate_phone',
            'quality',
            'username',
            'pwd',
            'email'
        ]);

        $data = $this->rmNullProps($data);

        if (isset($data['pwd'])) {
            if ($node->user_id) {
                $user = User::findOrFail($node->user_id);
                $user->fill([
                    'username' => $data['username'],
                    'pwd' => bcrypt($data['pwd']),
                    'email' => isset($data['email']) ? $data['email'] : '',
                ]);
                $user->save();
            } else {
                $user = new User();
                $user->fill([
                    'username' => $data['username'],
                    'pwd' => bcrypt($data['pwd']),
                    'email' => isset($data['email']) ? $data['email'] : '',
                    'type' => 5,
                    'platform_id' => $node->id
                ]);
                $user->save();
                $data['user_id'] = $user->id;
            }
        }


        $node->fill($data);
        if ($node->save()) {
            return $this->returnJSON(null, 0, '保存成功');
        }
        return $this->returnJSON(null, 500, '保存失败');
    }


    public function getTeamInfo(Request $request) {
        $user = $request->user();

        if ($user->type != 2) {
            throw new \Exception('只有团队用户才能获取团队信息');
        }

        $team = $user->team;
        $data = $team->toArray();

        if (isset($data['user_id'])) {
            $user = User::findOrFail($data['user_id']);
            $data['username'] = $user->username;
            $data['email'] = $user->email;
        }
        return $this->returnJSON($data);
    }

    public function saveTeamInfo(Request $request) {
        $user = $request->user();

        if ($user->type != 2) {
            throw new \Exception('只有团队用户才能保存团队信息');
        }

        $node = $user->team;
        $firstSave = $node->verify_status == -1;

        $this->validate($request, [
            'org_id' => 'required',
            'name' => 'required|max:32',
            'type' => 'required|max:32',
            'service_target' => 'required|max:32',
            'contact_name' => 'required|max:32',
            'contact_phone' => 'required|max:32',
            'contact_email' => 'required|max:255',
            'address' => 'required',
//            'legal_person' => 'required|max:12',
//            'legal_person_id' => 'required|max:18',
//            'legal_person_phone' => 'required|max:32',
            'abstract' => 'required',
            'username' => 'max:64',
            'pwd' => 'max:64',
            'slogan' => 'max:20'
        ]);

        $data = $request->only([
            'org_id',
            'logo',
            'name',
            'type',
            'service_target',
            'contact_name',
            'contact_phone',
            'contact_email',
            'contact_addr',
//            'legal_person',
//            'legal_person_id',
//            'legal_person_phone',
            'certificate_photo',
            'team_photo',
            'abstract',
            'username',
            'pwd',
            'acl',
            'slogan',
            'address'
        ]);
        $data['legal_person'] = '';
        $data['legal_person_id'] = '';
        $data['legal_person_phone'] = '';

        $data['logo'] = isset($data['logo']) ? $data['logo'] : '';
        $data['certificate_photo'] = isset($data['certificate_photo']) ? $data['certificate_photo'] : '';
        $data['team_photo'] = isset($data['team_photo']) ? $data['team_photo'] : '';
        $data['verify_status'] = 0;
        $data['slogan'] = isset($data['slogan']) ? $data['slogan'] : '';

        if (isset($data['acl'])) {
            $data['auth_exempt_project'] = strpos($data['acl'], "project-skip-verify") === false ? 0 : 1;
            $data['auth_create_team'] = strpos($data['acl'], "owner-subteam") === false ? 0 : 1;

            // 拥有子团队的人，自动就有项目免审权
            if ($data['auth_create_team']) {
                $data['auth_exempt_project'] = 1;
            }
        }

        if (isset($data['pwd'])) {
            if ($node->user_id) {
                $user = User::findOrFail($node->user_id);
                $user->fill([
                    'username' => $data['username'],
                    'pwd' => bcrypt($data['pwd']),
                    'email' => isset($data['email']) ? $data['email'] : '',
                    'team_id' => $node->id
                ]);
                $user->save();
            } else {
                $user = new User();
                $user->fill([
                    'username' => $data['username'],
                    'pwd' => bcrypt($data['pwd']),
                    'email' => isset($data['email']) ? $data['email'] : '',
                    'type' => 3,
                    'team_id' => $node->id
                ]);
                $user->save();
                $data['user_id'] = $user->id;
            }
        }


        $node->fill($data);
        if ($node->save()) {

            if ($user->type == 2 && $firstSave) {
                return $this->returnJSON(null, 0, '保存成功', 200, [
                    'UPDATE_USER_ACL' => $user->getAclList()
                ]);
            }

            return $this->returnJSON(null, 0, '保存成功');
        }
        return $this->returnJSON(null, 500, '保存失败');
    }

    public function getTeamAcl(Request $request) {
        $user = $request->user();

        if ($user->type != 2) {
            throw new \Exception('只有团队用户才能获取团队信息');
        }

        $node = $user->team;
        $data = $node->toArray();
        $data['user'] = $user;

        $acl = [];

        if (isset($data['auth_exempt_project']) && intval($data['auth_exempt_project'])) {
            $acl[] = 'project-skip-verify';
        }

        if (isset($data['auth_create_team']) && intval($data['auth_create_team'])) {
            $acl[] = 'owner-subteam';
        }

        $data['acl'] = join(",", $acl);

        return $this->returnJSON($data, 0, 'ok');
    }

    public function saveTeamAcl(Request $request) {
        $user = $request->user();

        if ($user->type != 2) {
            throw new \Exception('只有团队用户才能保存团队信息');
        }

        $node = $user->team;
        $data = $request->only([
            'join_type',
        ]);

        $node->fill($data);
        if ($node->save()) {
            return $this->returnJSON(null, 0, '保存成功');
        }
        return $this->returnJSON(null, 500, '保存失败');
    }

    public function inbox(Request $request) {
        $user = $request->user();
        $query = $user->inbox()->with('from.team', 'from.org');
        $perPage = $request->get('perPage', 10);
        $query->orderBy('publish_time', 'DESC');
        $info = $query->paginate($perPage)->toArray();

        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => array_map(function($item) {
                if (isset($item['from'])) {
                    if (isset($item['from']['team']) && $item['from']['type'] == 2) {
                        $item['from']['name'] = $item['from']['team']['name'];
                    }  else if (isset($item['from']['org']) && $item['from']['type'] == 3) {
                        $item['from']['name'] = $item['from']['org']['name'];
                    } else {
                        $item['from']['name'] = $item['from']['username'];
                    }
                }
                return $item;
            }, $info['data'])
        ], 0, '', 200, [
            'UPDATE_UNREAD_COUNT' => Message::where('to_user_id', '=', $user->id)->where('is_read', '=', 0)->count()
        ]);
    }

    public function outbox(Request $request) {
        $user = $request->user();
        $query = $user->outbox()->with('to');
//        echo $query->toSql();die;
        $perPage = $request->get('perPage', 10);
        $query->orderBy('publish_time', 'DESC');
        $info = $query->paginate($perPage)->toArray();

        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);
    }

    public function send(Request $request) {
        $this->validate($request, [
            'to' => 'required',
            'content' => 'required'
        ]);

        $node = new Message();
        $data = $request->only([
            'to',
            'title',
            'content'
        ]);

        $data['to_user_id'] = $data['to'];
        $data['from_user_id'] = $request->user()->id;
        $data['type'] = 1;

        $node->fill($data);

        if ($node->save()) {
            return $this->returnJSON(null, 0, '发送成功');
        }
        return $this->returnJSON(null, 500, '发送失败');
    }

    public function markread(Request $request, $id) {
        $user = $request->user();
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));

        $result = Message::whereIn('id',  $ids)->where('to_user_id', '=', $user->id)->update(['is_read' => 1]);

        if ($result) {
            return $this->returnJSON($ids, 0, '已成功标记已读', 200, [
                'UPDATE_UNREAD_COUNT' => Message::where('to_user_id', '=', $user->id)->where('is_read', '=', 0)->count()
            ]);
        } else {
            return $this->returnJSON(null, 1, "操作失败");
        }
    }


    public function verifyphone(Request $request) {

        $rules = [
            'phone' => 'required|is_phone',
        ];
        $validator = Validator::make(Input::all(), $rules);

        if($validator->fails())
        {
            $errors = $validator->errors();
            return $this->returnJSON(null, 10001, implode(' ', $errors->all()));
        }

        $phone = $request->input('phone');
        $ip = $request->getClientIp();

        $node = new SmsCode();
        $code = $node->getVerifyCode($phone, $ip, 1);

        if($code === false)
        {
            return $this->returnJSON(null, 20001, '手机号异常,发送验证码失败!');
        }

        $sms = new Sms();
        $ret = $sms->sendTemplateSMS($phone, array($code, '10分钟'),209261);

        if($ret->statusCode !== '000000')
        {
            return $this->returnJSON(null, 30001, $ret->statusMsg);
        }
        return $this->returnJSON(null);
    }

    public function bindPhone(Request $request)
    {
        $rules = [
            'phone' => 'required|is_phone',
            'code' => 'required',
        ];
        $validator = Validator::make(Input::all(), $rules);

        if($validator->fails())
        {
            $errors = $validator->errors();
            return $this->returnJSON(null, 10001, implode(' ', $errors->all()));
        }

        $phone = $request->input('phone');
        $verifyCode = $request->input('code');
        //检查验证码
        $checkSms = SmsCode::checkVerifyCode($phone, $verifyCode, 1);
        if( !$checkSms )
        {
            return $this->returnJSON(null, 10001, '短信验证码错误,请重新获取验证码!');
        }

        $user = $request->user();

        $user->fill(['phone'=>$phone]);
        if($user->save())
        {
            return $this->returnJSON(null);
        }
    }

    public function resetPwd(Request $request)
    {
        $rules = [
            'orgin_pwd' => 'required',
            'pwd' => 'required',
            'pwd_confirm' => 'required',
        ];
        $validator = Validator::make(Input::all(), $rules);

        if($validator->fails())
        {
            $errors = $validator->errors();
            return $this->returnJSON(null, 10001, implode(' ', $errors->all()));
        }

        $originPwd = $request->input('orgin_pwd');
        $pwd = $request->input('pwd');
        $confirmPwd = $request->input('pwd_confirm');

        if($pwd != $confirmPwd)
        {
            return $this->returnJSON(null, 10001, '两次的密码不一致!');
        }

        $user = $request->user();
        //密码错误
        if( !Hash::check($originPwd, $user->pwd))
        {
            return $this->returnJSON(null, 10001, '原始密码错误!');
        }

        $user->fill(['pwd' => bcrypt($pwd),]);
        if($user->save())
        {
            return $this->returnJSON(null);
        }
    }
}
